package com.cn.dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.*;

public  class BaseDao {
    static Connection connection = null;
    static PreparedStatement preparedStatement = null;
    static ResultSet resultSet = null;
    static Statement statement = null;




   /* //封装连接
    public static Connection getConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306//kgcnews";
            String user = "root";
            String pass = "123456";
            connection= DriverManager.getConnection(url,user,pass);

        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;

    }*/

    public static Connection getConnection(){
        try {
            Context context = new InitialContext();
            DataSource dataSource= (DataSource) context.lookup("java:comp/env/jdbc/news");
            connection=dataSource.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;

    }



    //查询
    public static ResultSet selectObj(String sql,Object[] objects){
        connection=BaseDao.getConnection();
        try {
            preparedStatement=connection.prepareStatement(sql);
            if (objects!=null){
                for (int i=0;i<objects.length;i++){
                    preparedStatement.setObject(i+1,objects[i]);
                }
                resultSet= preparedStatement.executeQuery();
            }
            resultSet= preparedStatement.executeQuery();

        }catch (Exception e){
            e.printStackTrace();
        }
        return resultSet;
    }



    //关闭资源
    public static void closeConnection(Connection connection ,PreparedStatement preparedStatement,ResultSet resultSet,Statement statement){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (preparedStatement!=null){
                preparedStatement.close();
            }
            if (statement!=null){
                statement.close();
            }
            if (connection!=null){
                connection.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
